package eu.news.interconnect.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import eu.news.interconnect.NewsEntity;
import eu.news.interconnect.Utils;

/**
 * 将本地信息发送到远程应用。
 */
public class ClientPusher {
	String accessKey;
	String message;
	
	public ClientPusher(String accessKey) {
		super();
		this.accessKey = accessKey;
	}

	public String getLastMessage(){
		return message;
	}
	
	public boolean send(NewsEntity news){
		if(news==null)
			return false;
		URL url = null;
		try {
			url = new URL("http://localhost:8080/exchange/"+accessKey);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.connect();
			conn.getOutputStream().write(Utils.getObjectBytes(news));
			conn.getOutputStream().flush();
			conn.getOutputStream().close();
			BufferedReader reader=new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line =null;
			StringBuffer buffer=new StringBuffer();
			while((line=reader.readLine())!=null)
				buffer.append(line);
			message=buffer.toString();
			System.out.println(message);
			if(message.length()>0)
				return false;
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return false;
	}
	
}
